<?php

namespace app\data\controller\record;

use app\admin\service\WxWorkService;
use app\data\service\CityUserRelationService;
use app\data\service\RecordService;
use app\data\service\ReworkService;
use app\data\service\StringParse;
use think\admin\Controller;
use think\facade\Cache;

/**
 * 未喷漆分析
 * Class CarRecordAnalyze
 * @package app\data\controller\user
 */
class CarRecordAnalyze extends Controller
{
    /**
     * 绑定数据表
     * @var string
     */
    private $table = 'data_record';

    /**
     * 未喷漆分析
     * @auth true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        // 批量分析原因
        RecordService::instance()->analyzeReasonBatch();
        $this->analyzeReasons = RecordService::instance()->analyzeReasons();

        $ts['ta'] = ['vip' => '', 'name' => '全部记录', 'count' => 0];
        $this->total = $ts;

        // 设置页面标题
        $this->title = '未喷漆分析';
        // 创建查询对象
        $query = $this->_query($this->table)->order('id desc');

        $result = $query->whereIn('paint_status', [-1, 0])->like('phone,username,plate_number')->equal('id,province#query_province,city#query_city,area#query_area,end_paint_status,fail_status,is_deal,is_rework')->dateBetween('time_docking,time_complete');

        // 列表选项卡
        $this->type = trim(input('type', 'ta'), 't');

        if ($this->type != 'a') {
            $query->where('analyze_reason', $this->type);
        }

        $uuidCityName = $this->request->request('uuid_city_name', '');
        if (!empty($uuidCityName)) {
            $uuidCityIds = $this->app->db->name('work_user')->where('name', 'like', "%{$uuidCityName}%")->column('id');
            $query->whereIn('uuid_city', $uuidCityIds);
        }

        // 数据查询分页
        if (input('output') == 'json') {
            $result = $result->page(true, false);
            $this->success('', $result);
        } else {
            $result->page();
        }
    }

    /**
     * 未喷漆分析导出
     * @auth true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function indexExport()
    {
        $this->index();
    }

    /**
     * 数据列表处理
     * @param array $data
     */
    protected function _indexExport_page_filter(array &$data)
    {
        $this->_page_filter($data);
    }

    /**
     * 数据列表处理
     * @param array $data
     */
    protected function _page_filter(array &$data)
    {
        foreach ($data as &$item) {
            $item['analyze_reason_text'] = RecordService::instance()->analyzeReasons($item['analyze_reason']);
        }
    }

    /**
     * 修改未喷漆原因
     * @auth true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function changeReason()
    {
        $data = $this->_vali([
            'id.require' => 'id不能为空！',
            'analyze_reason.require' => '分析原因不能为空！'
        ]);

        $record = $this->app->db->name($this->table)->where('id', $data['id'])->findOrEmpty();
        if (!$record) {
            $this->error('查无该记录信息');
        }

        $this->app->db->name($this->table)->where('id', $data['id'])->update(['analyze_reason' => $data['analyze_reason']]);

        $this->success('修改成功');
    }

    /**
     * 未喷漆原因分析
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function overview()
    {
        if ($this->request->isGet()) {
            $this->fetch();
        } else {
            $records = $this->app->db->name('data_record')
                ->group('analyze_reason')
                ->field('analyze_reason,COUNT(*) as count')
                ->whereIn('paint_status', [-1, 0])
                ->select()
                ->toArray();

            $count = 0;
            foreach ($records as $record) {
                $count += $record['count'];
            }

            foreach ($records as $record) {
                $num =  bcmul(bcdiv($record['count'], $count, 4), 100, 2);
                $response[] = [
                    'name' => (RecordService::instance()->analyzeReasons($record['analyze_reason']) ?: '未知')  . "{$num}%",
                    'value' => $num
                ];
            }

            $this->success('', $response ?? []);
        }
    }
}